import 'package:flutter/material.dart';

import 'log_list_page.dart';

void loggerToggleOverlay(BuildContext context, bool? show) {
  if (show == null) {
    show = !(_loggerEntranceDisplayed.value == true);
  }
  if (!show) {
    _loggerRemoveOverlay();
    return;
  }
  final o = Overlay.of(context);
  if (o != null && _loggerEntranceDisplayed.value == null) {
    Future.delayed(Duration(milliseconds: 20), () {
      if (_loggerEntranceDisplayed.value == null) {
        _loggerEntranceDisplayed.value = true;
        o.insert(_loggerOverlay);
      }
    });
  }
}

OverlayEntry _loggerOverlay = OverlayEntry(
  builder: (context) => _LoggerEntranceWidget(),
);

ValueNotifier<bool?> _loggerEntranceDisplayed = ValueNotifier(null);

class _LoggerEntranceWidget extends StatefulWidget {
  @override
  _LoggerEntranceWidgetState createState() => _LoggerEntranceWidgetState();
}

class _LoggerEntranceWidgetState extends State<_LoggerEntranceWidget> {
  double x = 0, y = 0;
  Size? screenSize;
  static const buttonSize = 56.0;
  static const buttonRadius = buttonSize / 2;

  @override
  Widget build(BuildContext context) {
    if (screenSize == null) {
      screenSize = MediaQuery.of(context).size;
      x = buttonSize;
      y = screenSize!.height - buttonSize;
    }
    return Stack(
      children: [
        Positioned(
          left: x - buttonRadius,
          top: y - buttonRadius,
          child: ValueListenableBuilder(
            valueListenable: _loggerEntranceDisplayed,
            builder: (BuildContext context, bool? value, Widget? child) {
              return value == true ? child! : Offstage();
            },
            child: Listener(
              onPointerMove: (event) {
                setState(() {
                  updateLocation(event);
                });
              },
              child: FloatingActionButton(
                backgroundColor: Colors.purple,
                child: Text("LOG"),
                onPressed: () async {
                  _loggerEntranceDisplayed.value = false;
                  await showLogMainPage(context);
                  _loggerEntranceDisplayed.value = true;
                },
              ),
            ),
          ),
        ),
      ],
    );
  }

  void updateLocation(PointerMoveEvent event) {
    x = event.position.dx;
    y = event.position.dy;
    if (x < buttonRadius) {
      x = buttonRadius;
    } else if (x > (screenSize!.width - buttonRadius)) {
      x = screenSize!.width - buttonRadius;
    }

    if (y < buttonSize) {
      y = buttonSize;
    } else if (y > (screenSize!.height - buttonRadius)) {
      y = screenSize!.height - buttonRadius;
    }
  }

  Future showLogMainPage(BuildContext context) {
    return Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => LogListPage()),
    );
  }
}

void _loggerRemoveOverlay() {
  if (_loggerEntranceDisplayed.value != null) {
    _loggerEntranceDisplayed.value = null;
    _loggerOverlay.remove();
  }
}
